package service

import (
	"github.com/jinzhu/gorm"
	"naio/config"
	"naio/db/mysql"
	"naio/errs"
	"naio/model"
)

type IGridCategoryService interface {
	GetGridCategoryList(page, size int) (*[]model.GridCategoryModel, int)
	GetGridCategoryById(id int) *model.GridCategoryModel
	GetGridCategoryByName(name string) *model.GridCategoryModel
	AddGridCategory(gridC *model.GridCategoryModel)
	UpdateGridCategory(gridC *model.GridCategoryModel)
	CountCategoryBindGrid(categoryId int) int
}

type GridCategoryService struct {
	Conf *config.BaseConfig
}

func NewGridCategoryService(conf *config.BaseConfig) IGridCategoryService{
	return &GridCategoryService{Conf: conf}
}

func (s GridCategoryService) AddGridCategory(gridC *model.GridCategoryModel) {
	db:=mysql.GetMysqlPool().GetMysqlDB()
	err := db.Create(gridC).Error
	if err != nil {
		panic(err)
	}
}

func (s GridCategoryService) UpdateGridCategory(gridC *model.GridCategoryModel) {
	db:=mysql.GetMysqlPool().GetMysqlDB()
	err := db.Save(gridC).Error
	if err != nil {
		panic(err)
	}
}

func (s GridCategoryService) GetGridCategoryByName(name string) *model.GridCategoryModel {
	db:=mysql.GetMysqlPool().GetMysqlDB()
	one := &model.GridCategoryModel{}
	err := db.Where("name=?", name).First(&one).Error
	if err == gorm.ErrRecordNotFound {
		panic(errs.NewMyAPIError(errs.ErrorGridCategoryNotExist, "宫格分类不存在"))
	}
	if err != nil {
		panic(err)
	}
	return one
}

func (s GridCategoryService) GetGridCategoryById(id int) *model.GridCategoryModel {
	db:=mysql.GetMysqlPool().GetMysqlDB()
	one := &model.GridCategoryModel{}
	err := db.Where("id=?", id).First(&one).Error
	if err == gorm.ErrRecordNotFound {
		panic(errs.NewMyAPIError(errs.ErrorGridCategoryNotExist, "宫格分类不存在"))
	}
	if err != nil {
		panic(err)
	}
	return one
}

func (s GridCategoryService) GetGridCategoryList(page, size int) (*[]model.GridCategoryModel, int) {
	db:=mysql.GetMysqlPool().GetMysqlDB()
	list := &[]model.GridCategoryModel{}
	var total int
	err := db.Where("del=0").Offset((page - 1) * size).Limit(size).Find(&list).Error
	if err != nil {
		panic(err)
	}
	db.Table("grid_category").Where("del=0").Count(&total)
	return list, total
}

func (s GridCategoryService) CountCategoryBindGrid(categoryId int) int {
	db:=mysql.GetMysqlPool().GetMysqlDB()
	var total int
	err := db.Table("grid_category").Where("del=0 AND category_id=?", categoryId).Count(&total).Error
	if err != nil {
		panic(err)
	}
	return total
}